<template>
  <section>
    <el-row>
      <el-col :span="24">
        <!--表单-->
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item>
            <el-input v-model="searchImei" placeholder="请输入设备IMEI、deviceId或设备名称" style="width: 300px;"></el-input>
          </el-form-item>
          <el-button type="primary" @click="onSubmit" style="margin-left:10px">查询</el-button>
          <el-button type="primary" @click="download" style="margin-left:10px" id="download">导出数据</el-button>
          <el-button type="primary" @click="downloadTemplate" style="float:right;margin-right:10px">下载模版</el-button>
          <el-upload style="float: right;"
          action="/upload/excel" :headers="headers"
               :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload" :show-file-list="false">
          <el-button type="primary">导入设备</el-button>
        </el-upload>
        </el-form>
        <!--表格-->
        <el-table
          :data="tableData.slice((currentPage - 1) * 10, currentPage * 10)"
          border
          style="width: 100%"
          @filter-change="fiterChangeEvent">
          <el-table-column
            prop="deviceName"
            label="设备名称"
            width="180">
          </el-table-column>
          <el-table-column
            prop="deviceId"
            label="设备ID"
            width="180">
          </el-table-column>
          <el-table-column
            prop="imei"
            label="IMEI"
            width="180">
          </el-table-column>
          <el-table-column
            prop="deviceStatus"
            label="状态"
            width="90"
            :formatter="formatSex" 
            :filters="[{ text: '已注册', value: 0 }, { text: '已激活', value: 1 }, { text: '已注销', value: 2 }]"
            :column-key="'deviceStatus'"
            filter-placement="bottom-end">
          </el-table-column>
          <el-table-column
            prop="netStatus"
            label="在线离线"
            width="90"
            :formatter="formatOnline"
            :filters="[{ text: '在线', value: 1 }, { text: '离线', value: 2 }]"
            :column-key="'netStatus'"
            filter-placement="bottom-end">
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            width="180" :formatter="formatCreateTime">
          </el-table-column>
          <el-table-column
            prop="onlineAt"
            label="最后上线时间"
            width="180" :formatter="formatOnlineAtTime">
          </el-table-column>
          <el-table-column
            prop="offlineAt"
            label="最后离线时间"
            width="180" :formatter="formatOfflineAtTime">
          </el-table-column>
          <el-table-column label="">
            <template scope="scope">
              <el-button type="primary" size="small" @click="handleDetail(scope.$index, scope.row)">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="10"
            layout="prev, pager, next, jumper"
            :total="tableData.length">
          </el-pagination>
        </div>
      </el-col>
    </el-row>
    <el-dialog title="导入设备详情"
        :visible.sync="dialogVisible"
        width="50%" :close-on-click-modal="false">
        <el-table
          :data="tableReport.slice((currentPageReport - 1) * 10, currentPageReport * 10)"
          border
          style="width: 100%">
          <el-table-column
            prop="result"
            label="结果"
            width="180" 
            :formatter="formatReportResult">
          </el-table-column>
          <el-table-column
            prop="imei"
            label="IMEI"
            width="180">
          </el-table-column>
          <el-table-column
            prop="reason"
            label="失败原因">
          </el-table-column>
        </el-table>
            <span slot="footer">
            <el-button type="primary" @click="confirm">确 定</el-button>
          </span>
          <el-pagination
            :current-page="currentPageReport"
            @current-change="handleCurrentChangeReport"
            :page-size="10"
            layout="prev, pager, next, jumper"
            :total="tableReport.length">
          </el-pagination>
      </el-dialog>
  </section>
</template>
<script type="text/ecmascript-6">
import debounce from 'lodash.debounce';
import { deviceService } from '@/services';
import utils from '@/utils.js';
import { mapState } from 'vuex';
export default {
  data () {
    const token = localStorage.getItem('token');
    return {
      tableData: [],
      platformValue: '',
      currentPage: 1,
      searchImei: '',
      deviceStatusFiter: '',
      netStatusFilter: '',
      headers: {token: token},
      dialogVisible: false,
      tableReport: [],
      currentPageReport: 1,
    };
  },
  activated () {
    this.getDeviceList();
  },
  computed: mapState({
    loginSysUserVo: (state) => state.loginSysUserVo,
  }),
  watch: {
    'loginSysUserVo': {
      handler: function() {
        if (this.loginSysUserVo) {
            const token = localStorage.getItem('token');
            this.headers = {token: token};
        }
      },
      deep: true,
    },
  },
  methods: {
    getDeviceList: debounce(async function() {
      this.tableData = await deviceService.getDeviceList(this.searchImei, this.platformValue, this.deviceStatusFiter, this.netStatusFilter);
    }, 500),
    onSubmit (e) {
      let target = e.target;
      // 根据button组件内容 里面包括一个span标签，如果设置icon，则还包括一个i标签，其他情况请自行观察。
      // 所以，在我们点击到button组件上的文字也就是span标签上时，直接执行e.target.blur()不会生效，所以要加一层判断。
      if (target.nodeName === 'SPAN' || target.nodeName === 'I') {
        target = e.target.parentNode;
      }
      target.blur();
      if (utils.isEmpty(this.searchImei)) {
        this.searchImei = "";
      }
      this.currentPage = 1;
      this.getDeviceList();
    },
    handleDetail (index, row) {
      var deviceId = row.deviceId;
      if(row.prodKey === '15134891' || row.prodKey === '15190721'){
        let { href } = this.$router.resolve({ path: '/deviceDetailProfileGC', query: { deviceId: deviceId } });
        window.open(href, '_blank');
      }else{
        if(row.platform==='master'){
          let { href } = this.$router.resolve({ path: '/deviceCommon', query: { deviceId: deviceId } });
           window.open(href, '_blank');
        }else{
          let { href } = this.$router.resolve({ path: '/deviceDetail', query: { deviceId: deviceId } });
           window.open(href, '_blank');
        }

      }
    },
    download: function(e) {
      let target = e.target;
      // 根据button组件内容 里面包括一个span标签，如果设置icon，则还包括一个i标签，其他情况请自行观察。
      // 所以，在我们点击到button组件上的文字也就是span标签上时，直接执行e.target.blur()不会生效，所以要加一层判断。
      if (target.nodeName === 'SPAN' || target.nodeName === 'I') {
        target = e.target.parentNode;
      }
      target.blur();

      var obj = document.getElementById('download');
      var str = "设备Id,设备名称,IMEI,状态,在离线,创建时间,最后上线时间,最后离线时间\n";
      for (var i = 0; i < this.tableData.length; i++) {
        var item = this.tableData[i];
        var devst = "";
        switch (item.deviceStatus) {
          case 0:
            devst = '已注册';
            break;
          case 1:
            devst = '已激活';
            break;
          case 2:
            devst = '已注销';
            break;
          default:
            devst = '未知';
            break;
        };
        var devsts = "";
        switch (item.netStatus) {
          case 1:
            devsts = '在线';
            break;
          default:
            devsts = '离线';
            break;
        }
        str += item.deviceId + ',' + ("\t" + item.deviceName.toString()) + ',' + ("\t" + item.imei.toString()) + ',' + devst + ',' + devsts + ',' + ("\t" + utils.timestampToTime(item.createTime)) + ',' + ("\t" + utils.timestampToTime(item.onlineAt)) + ',' + ("\t" + utils.timestampToTime(item.offlineAt));
        str += "\n";
      }
      console.log(obj)
      str = encodeURIComponent(str);
      console.log(str)
      // 通过创建a标签实现
        const link = document.createElement("a");
        link.href = "data:text/csv;charset=utf-8,\ufeff" + str;
        // 对下载的文件命名
        link.download =  "download.xlsx";
        link.click();
    },
    downloadTemplate: function(e) {
      let target = e.target;
      // 根据button组件内容 里面包括一个span标签，如果设置icon，则还包括一个i标签，其他情况请自行观察。
      // 所以，在我们点击到button组件上的文字也就是span标签上时，直接执行e.target.blur()不会生效，所以要加一层判断。
      if (target.nodeName === 'SPAN' || target.nodeName === 'I') {
        target = e.target.parentNode;
      }
      target.blur();
      window.open('https://121.199.61.205:1416/upload/exportTemplate');
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      if (process.env.NODE_ENV !== 'production') {
      // eslint-disable-next-line
        console.log(`当前页: ${val}`);
      }
    },
    handleCurrentChangeReport(val) {
      this.currentPageReport = val;
      if (process.env.NODE_ENV !== 'production') {
      // eslint-disable-next-line
        console.log(`当前页: ${val}`);
      }
    },
    confirm () {
      this.tableReport = [];
      this.currentPageReport = 1;
      this.dialogVisible = false;
    },
    formatReportResult(row, column) {
      switch (row.result) {
        case 0:
          return '成功';
        default:
          return '失败';
      }
    },
    formatOnline(row, column) {
      switch (row.netStatus) {
        case 1:
          return '在线';
        default:
          return '离线';
      }
    },
    formatSex(row, column) {
      switch (row.deviceStatus) {
        case 0:
          return '已注册';
        case 1:
          return '已激活';
        case 2:
          return '已注销';
        default:
          return '未知';
      }
    },
    formatCreateTime(row, column) {
      return utils.timestampToTime(row.createTime);
    },
    formatOnlineAtTime(row, column) {
      return utils.timestampToTime(row.onlineAt);
    },
    formatOfflineAtTime(row, column) {
        return utils.timestampToTime(row.offlineAt);
    },
    fiterChangeEvent(filters) {
       if(filters.deviceStatus !== undefined){
         this.deviceStatusFiter = '';
        filters.deviceStatus.forEach(element => {
          this.deviceStatusFiter += (element+',');
        });

       }else if(filters.netStatus !== undefined) {
          this.netStatusFilter = '';
          filters.netStatus.forEach(element => {
             this.netStatusFilter += (element+',');
          });
       }

       this.currentPage = 1;
       this.getDeviceList();
    },
    async getUploadReport (report_id) {
        this.tableReport =  await deviceService.getReportDetail(report_id);
        this.dialogVisible = true;
    },
    handleAvatarSuccess(res, file) {
      console.log("上传成功");
      console.log(res);
      if(res.code!==200){
        this.$alert(res.msg, '提示', {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
      }else {
            var de = '成功:'+res.data.success+',失败:'+res.data.failed;
            this.$confirm(de, '提示', {
              distinguishCancelAndClose: true,
              confirmButtonText: '确定',
              cancelButtonText: '查看导入详情'
            })
              .then(() => {
                  if(res.data.success>0){
                  this.currentPage = 1;
                  this.getDeviceList();
                }
              })
              .catch(action => {
                if(action === 'cancel') {
                   this.getUploadReport(res.data.report_id);
                }else{
                  if(res.data.success>0){
                    this.currentPage = 1;
                    this.getDeviceList();
                  }
                }
              });
      }
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }


      console.log("开始上传");
      return isLt2M;
    }
  }
};
</script>
<style>
  .el-pagination {
    text-align: center;
    margin-top: 30px;
  }
  .el-message-box__btns .cancel {
    float: right;
    margin-left: 10px;
  }
</style>
